<template>
  <basic-drawer
    :visible="visible"
    :title="title"
    ok-text="保存配置"
    @ok="handleSubmit"
    @open="handleBeforeOpen"
    @close="handleBeforeClose"
    @cancel="emits('update:visible', false)">
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical">
      <a-form-item
        field="name"
        label="规则名称"
        hide-asterisk
        asterisk-position="end"
        required>
        <a-input
          v-model="formData.name"
          :max-length="20"
          class="!w-100"
          placeholder="请输入规则名称">
        </a-input>
      </a-form-item>
      <a-form-item
        label="匹配规则"
        hide-asterisk
        asterisk-position="end"
        required
        class="rule-help-item">
        <matching-rule-view
          ref="matchingView"
          v-model="ruleGroups"
          class="w-full"></matching-rule-view>
      </a-form-item>
      <a-form-item
        field="action"
        label="执行策略"
        hide-asterisk
        asterisk-position="end"
        required>
        <template #label>
          <div class="flex flex-col">
            <span>执行策略</span>
            <span class="text-xs/5 text-5">规则生效时，执行指定动作</span>
          </div>
        </template>
        <a-select
          v-model="formData.action"
          placeholder="请选择执行动作"
          class="!w-100"
          :options="executionOptions"
          @change="setDefaultType" />
      </a-form-item>

      <section v-if="formData.action === 1" class="mb-6">
        <a-form-item
          label="响应类型"
          required
          hide-asterisk
          field="response_page.type">
          <a-select
            v-model="formData.response_page.type"
            class="!w-100"
            placeholder="请选择响应类型"
            @change="setDefaultCode">
            <a-option
              v-for="item in RESPONSE_TYPE_LIST"
              :key="item.value"
              :label="item.label"
              :value="item.value" />
          </a-select>
        </a-form-item>
        <a-form-item
          label="响应代码"
          required
          hide-asterisk
          field="response_page.code">
          <a-input-number
            v-model.number="formData.response_page.code"
            hide-button
            :precision="0"
            :max-length="30"
            class="!w-100"
            :disabled="formData.response_page.type === 1"
            placeholder="请输入响应代码"></a-input-number>
        </a-form-item>
        <a-form-item
          v-if="formData.response_page.type !== 1"
          label="响应内容"
          required
          hide-asterisk
          class="!mb-2"
          field="response_page.body">
          <a-textarea
            v-model="formData.response_page.body"
            :max-length="10000"
            show-word-limit
            :auto-size="{ minRows: 5, maxRows: 5 }"
            class="w-full h-fit"
            :placeholder="`请输入显示页面的${getOptionsLabel(
              RESPONSE_TYPE_LIST,
              formData.response_page.type
            )}`"></a-textarea>
        </a-form-item>
        <section
          v-if="formData.response_page.type !== 1"
          class="flex items-center gap-x-6px w-fit cursor-pointer"
          @click="previewWithNewPage(formData.response_page.body)">
          <a-link :hoverable="false">预览效果</a-link><i-icons-new-page />
        </section>
      </section>
      <a-form-item
        v-if="list.length && showPriority"
        field="order"
        label="执行优先级"
        hide-asterisk
        asterisk-position="end"
        required>
        <section class="flex flex-col">
          <a-select
            v-model="formData.order"
            placeholder="请选择执行优先级"
            class="!w-100"
            :options="priorityOptions" />
          <a-form-item
            v-if="formData.order === A_EXECUTION_PRIORITY.CUSTOM"
            field="priority"
            hide-label
            asterisk-position="end"
            class="!mb-0 mt-2"
            required>
            <a-select
              v-model="formData.priority"
              class="w-[336px]"
              placeholder="优先触发创建的规则，再触发选择的规则">
              <a-option
                v-for="item in list"
                :key="item.id"
                :label="item.name"
                :value="item.priority" />
            </a-select>
          </a-form-item>
          <span
            v-if="formData.order === A_EXECUTION_PRIORITY.CUSTOM"
            class="text-5 text-xs/5"
            >在此规则前执行</span
          >
        </section>
      </a-form-item>
    </a-form>
  </basic-drawer>
</template>
<script lang="ts" setup>
import type { WafListItem } from '@/apis/model/waf'
import {
  addApiWafApi,
  getApiWafGetApi,
  updateApiWafApi
} from '@/apis/modules/waf'
import type { IMatchingGroup } from '@/components/MatchingRule/types'
import { getFieldValue } from '@/components/MatchingRule/utils'
import { A_EXECUTION_PRIORITY, RESPONSE_TYPE_LIST } from '@/constants'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
import { omit } from 'lodash-es'
import { v4 as uuidV4 } from 'uuid'
interface IProps {
  visible: boolean
  record?: any
  list: WafListItem[]
  showPriority?: boolean
}
const props = withDefaults(defineProps<IProps>(), {
  visible: false,
  showPriority: true,
  list: () => []
})
interface IEmits {
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}
const emits = defineEmits<IEmits>()
const title = computed(() => (props?.record?.id ? '编辑规则' : '创建规则'))
const formRef = ref<FormInstance>()
const matchingView = ref()
const formData = ref({
  name: '',
  action: undefined,
  order: undefined,
  priority: undefined,
  scope: 3,
  module: 1,
  module_config: {},
  response_page: {
    type: 1,
    code: 403,
    body: ''
  }
})
const formRules = computed<{ [key: string]: FieldRule[] }>(() => {
  return {
    name: [
      {
        required: true,
        message: '请输入规则名称'
      }
    ],
    action: [
      {
        required: true,
        message: '请选择执行动作'
      }
    ],
    order: [
      {
        required: true,
        message: '请选择执行优先级'
      }
    ],
    priority: [
      {
        required: true,
        message: '请选择自定义规则'
      }
    ],
    'response_page.body': [{ required: true, message: '请输入响应内容' }],
    'response_page.code': [
      { required: true, message: '请输入响应代码' },
      {
        validator: (value, callback) => {
          if (!/^4\d{2}$/.test(value)) {
            callback('输入 4XX 状态代码')
          } else {
            callback()
          }
        }
      }
    ]
  }
})
const ruleGroups = ref<IMatchingGroup[]>([
  {
    uuid: uuidV4(),
    rules: [
      {
        uuid: uuidV4(),
        field: '',
        operator: '',
        value: '',
        custom_field: ''
      }
    ]
  }
])

const setDefaultType = (val: number) => {
  if (val === A_RESPONSE_TYPE.DEFAULT) {
    formData.value.response_page.code = 403
  } else {
    formData.value.response_page.code = undefined
  }
  formData.value.response_page.type = 1
}
const setDefaultCode = (val: number) => {
  if (val === 1) formData.value.response_page.code = 403
}
const { request } = useRequest(getApiWafGetApi, {
  success(res) {
    Object.assign(formData.value, res)
    if (!res?.response_page) {
      formData.value.response_page = {
        type: A_RESPONSE_TYPE.DEFAULT,
        code: 403,
        body: ''
      }
    }
    ruleGroups.value[0].rules = res.conditions.map((item) => {
      return {
        ...item,
        value:
          getFieldValue(item)!.count > 1 ? item.value : item.value.toString()
      }
    })
    if (props.list.length) {
      if (props.list.length === 1)
        return (formData.value.order = formData.value.priority)
      const priorityArr = props.list.map((item: WafListItem) => item.priority!)
      const min = Math.min(...priorityArr)
      const max = Math.max(...priorityArr)
      switch (+formData.value.priority!) {
        case min:
          formData.value.order = A_EXECUTION_PRIORITY.FIRST
          break
        case max:
          formData.value.order = A_EXECUTION_PRIORITY.LAST
          break
        default:
          formData.value.order = A_EXECUTION_PRIORITY.CUSTOM
      }
    } else {
      formData.value.order = formData.value.priority
    }
  }
})

const handleBeforeOpen = async () => {
  if (props.record) request({ id: props.record?.id })
}
const handleBeforeClose = async () => {
  await formRef.value?.resetFields()
  matchingView.value?.reset()
  emits('update:visible', false)
  formData.value.response_page = {
    type: 1,
    code: 403,
    body: ''
  }
}
async function handleSubmit() {
  const error = await formRef.value?.validate()
  const error1 = await matchingView.value.validate()
  if (error || !error1) return false
  const data: any = {
    ...omit(formData.value, 'priority'),
    conditions: ruleGroups.value[0].rules.map((item) => {
      return {
        ...item,
        value: !Array.isArray(item.value)
          ? item.value
            ? [item.value]
            : []
          : item.value.filter(Boolean)
      }
    }),
    id: props.record ? props.record?.id : undefined
  }
  if (formData.value.action === A_EXECUTION_TYPE.OBSERVE)
    data.response_page = null
  if (formData.value?.order === A_EXECUTION_PRIORITY.FIRST) {
    data.priority = 1
  } else if (formData.value?.order === A_EXECUTION_PRIORITY.LAST) {
    data.priority = props.list.length + 1
  } else {
    data.priority = formData?.value?.priority
  }
  const api_path = props.record ? updateApiWafApi : addApiWafApi
  api_path(data).then(() => {
    ToastUtils.success('保存成功')
    emits('update:visible', false)
    emits('refresh')
  })
}
</script>

<style lang="less" scoped></style>
